import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

typedef RefreshFeedbackCallback = void Function(
    BuildContext context,
    RefreshMode refreshState,
    double pulledExtent,
    double refreshTriggerPullDistance,
    double refreshIndicatorExtent,
    AxisDirection axisDirection,
    bool float,
    Duration completeDuration,
    bool enableInfiniteRefresh,
    bool success,
    bool noMore);

class RefreshHeader {
  /// Key
  final Key key;

  /// 方位
  final AlignmentGeometry alignment;

  /// 提示刷新文字
  final String refreshText;

  /// 准备刷新文字
  final String refreshReadyText;

  /// 正在刷新文字
  final String refreshingText;

  /// 刷新完成文字
  final String refreshedText;

  /// 刷新失败文字
  final String refreshFailedText;

  /// 没有更多文字
  final String noMoreText;

  /// 显示额外信息(默认为时间)
  final bool showInfo;

  /// 更多信息
  final String infoText;

  /// 背景颜色
  final Color bgColor;

  /// 字体颜色
  final Color textColor;

  /// 更多信息文字颜色
  final Color infoColor;

  /// 失败图标
  final IconData failImage;

  /// 完成图标
  final IconData doneImage;

  /// 没有更多图标
  final IconData noMoreImage;

  /// 方向箭头图标
  final IconData arrowImage;

  /// 将刷新动作传递给外部自定义布局
  final RefreshFeedbackCallback feedbackCallback;

  RefreshHeader(
      {this.key,
      this.alignment,
      this.refreshText,
      this.refreshReadyText,
      this.refreshingText,
      this.refreshedText,
      this.refreshFailedText,
      this.noMoreText,
      this.showInfo: true,
      this.infoText,
      this.bgColor: Colors.transparent,
      this.textColor: Colors.black,
      this.infoColor: Colors.teal,
      this.feedbackCallback,
      this.failImage,
      this.doneImage,
      this.noMoreImage,
      this.arrowImage});

  CustomHeader realHeader;
  Header getRealHeader() {
    RefreshControlBuilder customHeaderBuilder = (BuildContext context,
        RefreshMode refreshState,
        double pulledExtent,
        double refreshTriggerPullDistance,
        double refreshIndicatorExtent,
        AxisDirection axisDirection,
        bool float,
        Duration completeDuration,
        bool enableInfiniteRefresh,
        bool success,
        bool noMore) {
      if (feedbackCallback != null) {
        feedbackCallback(
            context,
            refreshState,
            pulledExtent,
            refreshTriggerPullDistance,
            refreshIndicatorExtent,
            axisDirection,
            float,
            completeDuration,
            enableInfiniteRefresh,
            success,
            noMore);
        return SizedBox();
      }
      return ClassicalHeaderWidget(
          key: key,
          refreshState: refreshState,
          refreshHeader: this,
          pulledExtent: pulledExtent,
          refreshTriggerPullDistance: refreshTriggerPullDistance,
          refreshIndicatorExtent: refreshIndicatorExtent,
          axisDirection: axisDirection,
          float: float,
          completeDuration: completeDuration,
          enableInfiniteRefresh: enableInfiniteRefresh,
          success: success,
          noMore: noMore);
    };

    /// 可在此设置 super 的默认属性值
    realHeader = CustomHeader(headerBuilder: customHeaderBuilder);
    return realHeader;
  }
}

class ClassicalHeaderWidget extends StatefulWidget {
  final RefreshHeader refreshHeader;
  final RefreshMode refreshState;
  final double pulledExtent;
  final double refreshTriggerPullDistance;
  final double refreshIndicatorExtent;
  final AxisDirection axisDirection;
  final bool float;
  final Duration completeDuration;
  final bool enableInfiniteRefresh;
  final bool success;
  final bool noMore;

  ClassicalHeaderWidget(
      {Key key,
      this.refreshState,
      this.refreshHeader,
      this.pulledExtent,
      this.refreshTriggerPullDistance,
      this.refreshIndicatorExtent,
      this.axisDirection,
      this.float,
      this.completeDuration,
      this.enableInfiniteRefresh,
      this.success,
      this.noMore})
      : super(key: key);

  @override
  ClassicalHeaderWidgetState createState() => ClassicalHeaderWidgetState();
}

class ClassicalHeaderWidgetState extends State<ClassicalHeaderWidget>
    with TickerProviderStateMixin<ClassicalHeaderWidget> {
  // 是否到达触发刷新距离
  bool _overTriggerDistance = false;

  bool get overTriggerDistance => _overTriggerDistance;

  set overTriggerDistance(bool over) {
    if (_overTriggerDistance != over) {
      // _overTriggerDistance
      //     ? _readyController.forward()
      //     : _restoreController.forward();
      _repeatController.repeat(reverse: true);
      _overTriggerDistance = over;
    }
  }

  /// 默认语言
  GlobalEasyRefreshLocalizations _localizations =
      GlobalEasyRefreshLocalizations();

  /// 文本
  String get _refreshText {
    return widget.refreshHeader.refreshText ??
        (GlobalEasyRefreshLocalizations.of(context) == null
            ? _localizations.pullToRefresh
            : GlobalEasyRefreshLocalizations.of(context).pullToRefresh);
  }

  String get _refreshReadyText {
    return widget.refreshHeader.refreshReadyText ??
        (GlobalEasyRefreshLocalizations.of(context) == null
            ? _localizations.releaseToRefresh
            : GlobalEasyRefreshLocalizations.of(context).releaseToRefresh);
  }

  String get _refreshingText {
    return widget.refreshHeader.refreshingText ??
        (GlobalEasyRefreshLocalizations.of(context) == null
            ? _localizations.refreshing
            : GlobalEasyRefreshLocalizations.of(context).refreshing);
  }

  String get _refreshedText {
    return widget.refreshHeader.refreshedText ??
        (GlobalEasyRefreshLocalizations.of(context) == null
            ? _localizations.refreshed
            : GlobalEasyRefreshLocalizations.of(context).refreshed);
  }

  String get _refreshFailedText {
    return widget.refreshHeader.refreshFailedText ??
        (GlobalEasyRefreshLocalizations.of(context) == null
            ? _localizations.refreshFailed
            : GlobalEasyRefreshLocalizations.of(context).refreshFailed);
  }

  String get _noMoreText {
    return widget.refreshHeader.noMoreText ??
        (GlobalEasyRefreshLocalizations.of(context) == null
            ? _localizations.noMore
            : GlobalEasyRefreshLocalizations.of(context).noMore);
  }

  String get _infoText {
    return widget.refreshHeader.infoText ??
        (GlobalEasyRefreshLocalizations.of(context) == null
            ? _localizations.updateAt
            : GlobalEasyRefreshLocalizations.of(context).updateAt);
  }

  // 是否刷新完成
  bool _refreshFinish = false;

  set refreshFinish(bool finish) {
    if (_refreshFinish != finish) {
      if (finish && widget.float) {
        Future.delayed(widget.completeDuration - Duration(milliseconds: 400),
            () {
          if (mounted) {
            _floatBackController.forward();
            // _repeatController.stop();
          }
        });
        Future.delayed(widget.completeDuration, () {
          _floatBackDistance = null;
          _refreshFinish = false;
        });
      }
      _refreshFinish = finish;
    }
  }

  // 动画
  // AnimationController _readyController;
  // Animation<double> _readyAnimation;
  // AnimationController _restoreController;
  // Animation<double> _restoreAnimation;
  AnimationController _floatBackController;
  Animation<double> _floatBackAnimation;

  /// 上下移动动画
  AnimationController _repeatController;
  Animation<double> _repeatAnimation;

  // Icon旋转度
  // double _iconRotationValue = 1.0;

  // padding上下值
  double _paddingValue = 0.0;

  // 浮动时,收起距离
  double _floatBackDistance;

  // 显示文字
  String get _showText {
    if (widget.noMore) return _noMoreText;
    if (widget.enableInfiniteRefresh) {
      if (widget.refreshState == RefreshMode.refreshed ||
          widget.refreshState == RefreshMode.inactive ||
          widget.refreshState == RefreshMode.drag) {
        return _finishedText;
      } else {
        return _refreshingText;
      }
    }
    switch (widget.refreshState) {
      case RefreshMode.refresh:
        return _refreshingText;
      case RefreshMode.armed:
        return _refreshingText;
      case RefreshMode.refreshed:
        return _finishedText;
      case RefreshMode.done:
        return _finishedText;
      default:
        if (overTriggerDistance) {
          return _refreshReadyText;
        } else {
          return _refreshText;
        }
    }
  }

  // 刷新结束文字
  String get _finishedText {
    if (!widget.success) return _refreshFailedText;
    if (widget.noMore) return _noMoreText;
    return _refreshedText;
  }

  // 刷新结束图标
  IconData get _finishedIcon {
    if (!widget.success)
      return widget.refreshHeader.failImage ?? Icons.error_outline;
    if (widget.noMore)
      return widget.refreshHeader.noMoreImage ?? Icons.hourglass_empty;
    return widget.refreshHeader.doneImage ?? Icons.done;
  }

  // 更新时间
  DateTime _dateTime;

  // 获取更多信息
  String get _infoTextStr {
    if (widget.refreshState == RefreshMode.refreshed) {
      _dateTime = DateTime.now();
    }
    String fillChar = _dateTime.minute < 10 ? "0" : "";
    return _infoText.replaceAll(
        "%T", "${_dateTime.hour}:$fillChar${_dateTime.minute}");
  }

  @override
  void initState() {
    super.initState();
    // 初始化时间
    _dateTime = DateTime.now();
    // 准备动画
    // _readyController = new AnimationController(
    //     duration: const Duration(milliseconds: 200), vsync: this);

    // _readyAnimation = new Tween(begin: 0.5, end: 1.0).animate(_readyController)
    //   ..addListener(() {
    //     setState(() {
    //       if (_readyAnimation.status != AnimationStatus.dismissed) {
    //         _iconRotationValue = _readyAnimation.value;
    //       }
    //     });
    //   });
    // _readyAnimation.addStatusListener((status) {
    //   if (status == AnimationStatus.completed) {
    //     _readyController.reset();
    //   }
    // });
    // // 恢复动画
    // _restoreController = new AnimationController(
    //     duration: const Duration(milliseconds: 200), vsync: this);
    // _restoreAnimation =
    //     new Tween(begin: 1.0, end: 0.5).animate(_restoreController)
    //       ..addListener(() {
    //         setState(() {
    //           if (_restoreAnimation.status != AnimationStatus.dismissed) {
    //             _iconRotationValue = _restoreAnimation.value;
    //           }
    //         });
    //       });
    // _restoreAnimation.addStatusListener((status) {
    //   if (status == AnimationStatus.completed) {
    //     _restoreController.reset();
    //   }
    // });
    // float收起动画
    _floatBackController = new AnimationController(
        duration: const Duration(milliseconds: 300), vsync: this);
    _floatBackAnimation =
        new Tween(begin: widget.refreshIndicatorExtent, end: 0.0)
            .animate(_floatBackController)
              ..addListener(() {
                setState(() {
                  if (_floatBackAnimation.status != AnimationStatus.dismissed) {
                    _floatBackDistance = _floatBackAnimation.value;
                  }
                });
              });
    _floatBackAnimation.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _floatBackController.reset();
      }
    });

    /// 重复上下移动动画
    _repeatController = AnimationController(
        duration: const Duration(milliseconds: 800), vsync: this);
    Animation curve =
        CurvedAnimation(parent: _repeatController, curve: Curves.fastOutSlowIn);
    _repeatAnimation = Tween(begin: 0.0, end: 20.0).animate(curve)
      ..addListener(() {
        setState(() {
          if (_repeatAnimation.status != AnimationStatus.dismissed) {
            // print("_repeatController:---------------${_repeatAnimation.value}");
            _paddingValue = _repeatAnimation.value;
          }
        });
      });
  }

  @override
  void dispose() {
    // _readyController.dispose();
    // _restoreController.dispose();
    _floatBackController.dispose();

    _repeatController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // // 是否反向
    // bool isReverse = widget.axisDirection == AxisDirection.up ||
    //     widget.axisDirection == AxisDirection.left;
    // 是否到达触发刷新距离
    overTriggerDistance = widget.refreshState != RefreshMode.inactive &&
        widget.pulledExtent >= widget.refreshTriggerPullDistance;
    // print('widget.refreshState------:${widget.refreshState}');
    if (widget.refreshState == RefreshMode.refreshed) {
      refreshFinish = true;
    }
    // if (widget.refreshState == RefreshMode.refreshed ||
    //     widget.refreshState == RefreshMode.done ||
    //     (widget.enableInfiniteRefresh &&
    //         widget.refreshState != RefreshMode.refreshed) ||
    //     widget.noMore) {
    if (widget.refreshState == RefreshMode.done ||
        widget.refreshState == RefreshMode.inactive) {
      // 数据加载结束时，不论失败成功有没有数据等细节，结束重复动画
      _repeatController.stop();
    }
    return Stack(
      children: <Widget>[
        Positioned(
          left: 0.0,
          right: 0.0,
          bottom: 0.0,
          child: Container(
              width: double.infinity,
              height: _floatBackDistance == null
                  ? (widget.refreshIndicatorExtent > widget.pulledExtent
                      ? widget.refreshIndicatorExtent
                      : widget.pulledExtent)
                  : widget.refreshIndicatorExtent,
              color: widget.refreshHeader.bgColor,
              child: SizedBox(
                height: widget.refreshIndicatorExtent,
                width: double.infinity,
                child: Stack(
                  alignment: Alignment.center,
                  children: <Widget>[
                    // 总高度60.0
                    Positioned(
                      bottom: 0.0,
                      height: 6,
                      child: CustomPaint(
                        size: Size(22, 1),
                        painter: OvalPainter(),
                      ),
                    ),
                    Positioned(
                      top: 0.0,
                      bottom: -36.0,
                      child: Container(
                        padding: EdgeInsets.only(bottom: _paddingValue),
                        child: Image.asset(
                          'assets/images/block_icon.png',
                          width: 40,
                          height: 40,
                        ),
                      ),
                    ),
                  ],
                ),
              )),
        )

        // Positioned(
        //   top: isReverse
        //       ? _floatBackDistance == null
        //           ? 0.0
        //           : (widget.refreshIndicatorExtent - _floatBackDistance)
        //       : null,
        //   bottom: !isReverse
        //       ? _floatBackDistance == null
        //           ? 0.0
        //           : (widget.refreshIndicatorExtent - _floatBackDistance)
        //       : null,
        //   left: 0.0,
        //   right: 0.0,
        //   child: Container(
        //     alignment: widget.refreshHeader.alignment ?? isReverse
        //         ? Alignment.topCenter
        //         : Alignment.bottomCenter,
        //     width: double.infinity,
        //     height: _floatBackDistance == null
        //         ? (widget.refreshIndicatorExtent > widget.pulledExtent
        //             ? widget.refreshIndicatorExtent
        //             : widget.pulledExtent)
        //         : widget.refreshIndicatorExtent,
        //     color: widget.refreshHeader.bgColor,
        //     child: SizedBox(
        //         height: widget.refreshIndicatorExtent,
        //         width: double.infinity,
        //         child: Row(
        //           mainAxisAlignment: MainAxisAlignment.center,
        //           children: _buildContent(isReverse),
        //         )),
        //   ),
        // ),
      ],
    );
  }

  // // 构建显示内容
  // List<Widget> _buildContent(bool isReverse) {
  //   return <Widget>[
  //     Expanded(
  //       flex: 2,
  //       child: Container(
  //         alignment: Alignment.centerRight,
  //         padding: EdgeInsets.only(
  //           right: 10.0,
  //         ),
  //         child: (widget.refreshState == RefreshMode.refresh ||
  //                     widget.refreshState == RefreshMode.armed) &&
  //                 !widget.noMore
  //             ? Container(
  //                 width: 20.0,
  //                 height: 20.0,
  //                 child: CircularProgressIndicator(
  //                   strokeWidth: 2.0,
  //                   valueColor: AlwaysStoppedAnimation(
  //                     widget.refreshHeader.textColor,
  //                   ),
  //                 ),
  //               )
  //             : widget.refreshState == RefreshMode.refreshed ||
  //                     widget.refreshState == RefreshMode.done ||
  //                     (widget.enableInfiniteRefresh &&
  //                         widget.refreshState != RefreshMode.refreshed) ||
  //                     widget.noMore
  //                 ? Icon(
  //                     _finishedIcon,
  //                     color: widget.refreshHeader.textColor,
  //                   )
  //                 : Transform.rotate(
  //                     child: Icon(
  //                       isReverse
  //                           ? (widget.refreshHeader.arrowImage ??
  //                               Icons.arrow_upward)
  //                           : (widget.refreshHeader.arrowImage ??
  //                               Icons.arrow_downward),
  //                       color: widget.refreshHeader.textColor,
  //                     ),
  //                     angle: 2 * pi * _iconRotationValue,
  //                   ),
  //       ),
  //     ),
  //     Expanded(
  //       flex: 3,
  //       child: Column(
  //         crossAxisAlignment: CrossAxisAlignment.center,
  //         mainAxisAlignment: MainAxisAlignment.center,
  //         children: <Widget>[
  //           Text(
  //             _showText,
  //             style: TextStyle(
  //               fontSize: 16.0,
  //               color: widget.refreshHeader.textColor,
  //             ),
  //           ),
  //           widget.refreshHeader.showInfo
  //               ? Container(
  //                   margin: EdgeInsets.only(
  //                     top: 2.0,
  //                   ),
  //                   child: Text(
  //                     _infoTextStr,
  //                     style: TextStyle(
  //                       fontSize: 12.0,
  //                       color: widget.refreshHeader.infoColor,
  //                     ),
  //                   ),
  //                 )
  //               : Container(),
  //         ],
  //       ),
  //     ),
  //     Expanded(
  //       flex: 2,
  //       child: SizedBox(),
  //     ),
  //   ];
  // }
}

class OvalPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final Paint customPaint = Paint()..color = Color.fromRGBO(240, 240, 240, 1.0);
    canvas.drawOval(
        Rect.fromCenter(
            center: Offset(size.width / 2.0, size.height / 2.0),
            width: size.width,
            height: size.height),
        customPaint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}
